package cn.sytton.taffecloud.gateway.handler;

import cn.sytton.taffecloud.common.base.constants.ExceptionMessage;
import cn.sytton.taffecloud.gateway.util.WebFluxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 *
 * @author skyrock
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        String msg;
        HttpStatus status;
        if (ex instanceof ResponseStatusException) {
            ResponseStatusException rse = (ResponseStatusException) ex;
            status = rse.getStatus();
            msg = rse.getMessage();
        } else {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            msg = ExceptionMessage.ERROR;
        }

        log.error("[网关异常]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage(), ex);

        return WebFluxUtil.webFluxResponseWriter(response, status, msg);
    }
}